<template>
<div class="dashboard-container">
    <div class="app-container">
        <!-- 放置头部内容 -->
        <PageTools :showBefore="true">
            <span slot="before">共{{this.page.total}}条记录</span>
            <template slot="after">
                <el-button size="small" :disabled="!checkPermission('import')" type="warning" @click="$router.push('/import')">导入员工</el-button>
                <el-button size="small" :disabled="!checkPermission('export')" type="danger" @click="exportDate">导出员工</el-button>
                <el-button size="small" :disabled="!checkPermission('POINT-USER-ADD')" type="primary" @click="showDialog = true">新增员工</el-button>
            </template>
        </PageTools>
        <!-- 放置表格内容 和 分页组件 -->
        <el-card>
            <!-- 表格数据 -->
            <el-table border="" v-loading="loading" :data="UserList">
                <el-table-column label="序号" sortable="" type="index"></el-table-column>
                <el-table-column label="姓名" sortable="" prop="username"></el-table-column>
                <el-table-column label="头像" align="center">
                    <!-- 使用作用域插槽 获取当前数据 -->
                    <!-- 在表格中放置用户头像 -->
                    <template slot-scope="{row}">
                        <img :src="row.staffPhoto" alt="" style="border-radius: 50%; width: 100px; height: 100px; padding: 10px" v-imagError="require('@/assets/common/head.jpg')" @click="showCode(row.staffPhoto)">
                    </template>
                </el-table-column>
                <el-table-column label="工号" sortable="" prop="workNumber"></el-table-column>
                <el-table-column label="聘用形式" sortable="" prop="formOfEmployment" :formatter="formatEmployment"></el-table-column>
                <el-table-column label="部门" sortable="" prop="departmentName"></el-table-column>
                <el-table-column label="入职时间" sortable="" prop="timeOfEntry">
                    <!-- 作用域插槽 -->
                    <template slot-scope="{row}">
                        {{
                row.timeOfEntry | formatDate
              }}
                    </template>
                </el-table-column>
                <el-table-column label="账户状态" sortable="" prop="enableState">
                    <!-- 作用域插槽 结构出数据 -->
                    <template slot-scope="{row}">
                        <el-switch :value="row.enableState === 1">
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作" sortable="" fixed="right" width="280">
                    <template slot-scope="{row}">
                        <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
                        <el-button type="text" size="small">转正</el-button>
                        <el-button type="text" size="small">调岗</el-button>
                        <el-button type="text" size="small">离职</el-button>
                        <el-button type="text" size="small" @click="editRole(row.id)">角色</el-button>
                        <el-button type="text" :disabled="!checkPermission('point-user-delete')" size="small" @click="delEmployee(row.id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" style="height:60px" align="middle">
            <el-pagination background layout="prev, pager, next" :total="page.total" :current-page="page.page" @current-change="changePage">
            </el-pagination>
        </el-row>
    </div>
    <!-- 弹层组件 -->
    <!-- sync修饰符 是 子组件 去改变父组件的数据时的一个语法糖 可以简化我们的代码 -->
    <add-employee :showDialog="showDialog" />
    <el-dialog title="二维码" :visible.sync="showCodeDialog">
        <el-row type="flex" justify="center">
            <canvas ref="Mycanvas"></canvas>
        </el-row>
    </el-dialog>
    <!-- 放置分配角色弹出层 -->
    <assign-role :showRoleDialog.sync="showRoleDialog" :userId="userId" ref="assignRole"/>
</div>
</template>

<script>
import { getEmployeeList,delEmployee } from '@/api/employees'
import EmployeeEnum from '@/api/constant/employees'
import AddEmployee from './components/add-employee.vue'
import AssignRole from './components/assign-role.vue'
import {formatDate} from '@/filters'
import QrCode from 'qrcode'
export default {
    data() {
        return {
            UserList: [],
            page: {
                page: 1,
                size: 10,
                total: 0
            },
            loading: false, //显示遮罩层
            value: true, //显示隐藏状态开关
            showDialog: false, //显示弹层
            showCodeDialog: false, //控制二维码弹层的显示隐藏
            showRoleDialog:false,//控制显示角色分配弹出层
            userId:null,
        }
    },
    components: {
        AddEmployee,
        AssignRole
    },
    created() {
        this.getEmployeeList()
    },
    methods: {
        async getEmployeeList() {
            this.loading = true
            const {
                total,
                rows
            } = await getEmployeeList(this.page)
            this.page.total = total
            this.UserList = rows
            this.loading = false
        },
        async delEmployee(id) {
            try {
                await this.$confirm('确定要删除该员工吗？')
                await delEmployee(id)
                this.getEmployeeList()
                this.$message.success('删除成功！')
            } catch (error) {
                console.log(error)
            }
        },
        changePage(newPage) {
            this.page.page = newPage
            this.getEmployeeList()
        },
        formatEmployment(row, column, cellValue, index) {
            const obj = EmployeeEnum.hireType.find(item => item.id === cellValue)
            return obj ? obj.value : '未知形式'
        },
        exportDate() {
            const headers = {
                '姓名': 'username',
                '手机号': 'mobile',
                '入职日期': 'timeOfEntry',
                '聘用形式': 'formOfEmployment',
                '转正日期': 'correctionTime',
                '工号': 'workNumber',
                '部门': 'departmentName'
            }
            //导出excel
            import('@/vendor/Export2Excel').then(async excel => {
                //excel是引入文件的导出对象
                const {
                    rows
                } = await getEmployeeList({
                    page: 1,
                    size: this.page.total
                })
                const data = this.formatJson(headers, rows)
                excel.export_json_to_excel({
                    header: Object.keys(headers), //表头
                    data, //表格数据
                    filename: '员工资料表', //表名
                    multiHeader, //复杂表头 [['a','b','c'],[1,2,3]]
                    merges //合并单元格 ['A1:A2','B1:F1']
                })
            })
        },
        formatJson(headers, rows) {
            return rows.map(item => {
                //item是一个对象
                return Object.keys(headers).map(obj => {
                    // 需要判断一下字段
                    if (headers[obj] === 'timeOfEntry' || headers[obj] === 'correctionTime') {
                        // 格式化日期类型的数据
                        return formatDate(item[headers[obj]])
                    } else if (headers[obj] === 'formOfEmployment') {
                        const isReapet = EmployeeEnum.hireType.find(items => items.id === item[headers[obj]])
                        return isReapet ? isReapet.value : '未知'
                    }
                    return item[headers[obj]]
                })
            })
        },
        showCode(url) {
            if (url) { //有url的情况下才弹出层
                this.showCodeDialog = true //点击图片显示弹出层
                this.$nextTick(() => { //$nextTick的意思是 等一个页面渲染完毕 上一个数据更新之后执行
                    // 此时就可以确定 页面已经加载完成 有ref对象了
                    QrCode.toCanvas(this.$refs.Mycanvas, url) //调用二维码生成接口 生成二维码
                })
            } else { //url没有的情况下 则弹出提示
                this.$message.warning('该用户还没有上传头像')
            }
        },
        async editRole(id){
          this.userId = id,
          // console.log(this.userId);
          // 点击角色时 调用子组件的方法 然后获取数据
         await this.$refs.assignRole.getUserDetailById(id)
         this.showRoleDialog = true //显示弹出层
        }

    },

}
</script>

<style>

</style>
